package com.taobao.auth.utils;

import com.taobao.ucenter.model.dto.WebChatRequestDto;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;


/**
 * 验证消息的确来自微信服务器
 */
public class WebChatUtils {

    /**
     * 微信公众平台-测试公众号-接口配置信息-token
     */
    private static String webChatToken = "wxtoken";

    /**
     * 核实微信的请求
     */
    public static boolean checkWebChat(WebChatRequestDto webChatRequestDto) throws NoSuchAlgorithmException {

        // 将token、timestamp、nonce三个参数进行字典序排序
        String[] array = {webChatToken, webChatRequestDto.getTimestamp(), webChatRequestDto.getNonce()};
        Arrays.sort(array);

        // 将三个参数字符串拼接成一个字符串进行sha1加密
        String str = String.join("", array);
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
        byte[] digest = messageDigest.digest(str.getBytes());

        // 将加密后的字符串转换为十六进制数据，再转字符串
        StringBuilder hexString = new StringBuilder();
        for (byte b : digest) {
            String shaHex = Integer.toHexString(b & 0xFF);
            if (shaHex.length() == 1) {
                hexString.append(0);
            }
            hexString.append(shaHex);
        }

        // 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        return webChatRequestDto.getSignature().equals(hexString.toString());

    }
}
